const model = require('../../public/model/env.js');
const background = tt.getStorageSync('background');
const url = model.api_pro_url();
const key = model.key();
const appid = model.appid();

Page({
  data: {
    className: background === 'naight' ? 'containerdark' : 'containerlight',
    _value: '',
    data2: "免费获取卦象内容",
    showModal: true,
    zhihuidashi: "您好，道友",
    overbtn: "领 取",
    buttonDisableds: false,
    responseData: "",
    value1: '',
    value2: '',
    value3: '',
    number1: 0,
    number2: 0,
    number3: 0,
    userInfo: "",
    opfrom: "",
    anonymousCode: "",
    op_num: 0,
    login: tt.getStorageSync('userid') === '' ? 'login' : '',
    buttonDisabled: true,
    countDown: 1, // 初始化倒计时为3秒
    // lingqu: "领取",

  },

  remove() {
    this.setData({ _value: null });
  },

  bindInput(e, field) {
    const value = e.detail.value;
    this.setData({
      [field]: value,
      [`number${field.charAt(field.length - 1)}`]: value.length,
    });
  },

  one(e) { this.bindInput(e, 'value1'); },
  two(e) { this.bindInput(e, 'value2'); },
  three(e) { this.bindInput(e, 'value3'); },

  requestgua() {
    console.log('datainput');
    const { value1, value2, value3 } = this.data;

    if (![value1, value2, value3].every(value => /^\d{3}$/.test(value) && parseInt(value) > 100)) {
      return tt.showToast({
        title: '请正确输入三位数字',
        icon: 'none',
        duration: 2000
      });
    } else {
      const datainput = {
        value1,
        value2,
        value3,
      };
      tt.setStorageSync('datainput', datainput);

      this.setData({ buttonDisableds: true });

      tt.navigateTo({ url: '../setting/setting?value1=' + value1 + '&value2=' + value2 + '&value3=' + value3 });



    }
  },
  startCountDown() {
    let countDown = this.data.countDown;
    const intervalId = setInterval(() => {
      if (countDown <= 0) {
        clearInterval(intervalId);
        this.setData({
          buttonDisabled: false,
          countDown: '',

        });
      } else {
        countDown--;
        this.setData({ countDown });
      }
    }, 1000);
  },

  onLoad() {



    const fromcode = tt.getStorageSync('fromcode');
    console.log("onLoaduserid：", tt.getStorageSync('userid'));

    if (fromcode !== undefined) {
      this.setData({
        opfrom: `第${fromcode}封邀请函`,
        op_num: fromcode,
      });

    }
    const storedShowModal = tt.getStorageSync('showModal');
    console.log(storedShowModal);
    if (storedShowModal === false) {
      this.setData({ showModal: storedShowModal });
    }
    tt.request({
      url: `${url}/index.php/api/output`,
      data: { appid, key },
      method: 'POST',
      header: { 'content-type': 'application/json' },
      dataType: 'json',
      success: (res) => {
        this.setData({ responseData: res.data.data[0].jsontxt });
      },
      fail: (err) => {
        console.error('请求输出失败', err);
        tt.showToast({ title: '请求输出失败', icon: 'none', duration: 2000 });
      },
    });

    if (!this.data.login) return;

    tt[this.data.login]({
      force: true,
      success: (res) => {
        tt.request({
          url: `${url}/index.php/api/login`,
          data: { appid, key, code: res.code, anonymous_code: res.anonymousCode },
          method: 'POST',
          header: { 'content-type': 'application/json' },
          dataType: 'json',
          success: (res) => {
            this.startCountDown();
            tt.setStorageSync('unionid', res.data.unionid);
            tt.setStorageSync('open_id', res.data.open_id);

          },
          fail: (err) => {
            console.error('登录请求失败', err);
            tt.showToast({ title: '登录请求失败', icon: 'none', duration: 2000 });
          },
        });
      },
      fail: () => {
        console.error('登录调用失败');
        tt.showToast({ title: '登录调用失败', icon: 'none', duration: 2000 });
      },
    });
  },

  closeModal() {
    this.setData({ showModal: false });

  },

  over() { this.closeModal(); },

  getUserInfo(res) {

    const { userInfo } = res.detail;
    if (!userInfo) return;

    this.setData({
      userInfo,
      showModal: false,
    });

    tt.setStorageSync('userInfo', userInfo);
    tt.setStorageSync('user_icon', userInfo.avatarUrl);
    tt.setStorageSync('showModal', false);
    tt.showToast({ title: userInfo.nickName, icon: 'success', duration: 2000 });
    // console.log(tt.getStorageSync('showModal'));
    const getuserid = {
      url: `${url}/index.php/api/getuserid.php`,
      data: {
        key: key,
        open_id: tt.getStorageSync('open_id'),
        unionid: tt.getStorageSync('unionid'),
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(getuserid);
    tt.request({
      ...getuserid,
      success: (res) => {
        const data = res.data;
        console.log(data.data[0].id);
        tt.setStorageSync('userid', data.data[0].id);
        this.jifenaddnew(data.data[0].id);

      },
      fail: (err) => {
        console.error('请求输出失败', err);
        tt.showToast({ title: '保存失败', icon: 'none', duration: 2000 });
      },
    });


    tt.getSystemInfo({
      success(res) {
        // console.log(res.model);

        const sev = {
          url: `${url}/index.php/api/sev_user.php`,
          data: {
            key: key,
            open_id: tt.getStorageSync('open_id'),
            hao: res.model,
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
          },
          method: 'GET',
          header: {
            'content-type': 'application/json'
          },
          dataType: 'json',
        };
        console.log(sev);
        tt.request({
          ...sev,
          success: (res) => {
            console.log(res.data);


          },
          fail: (err) => {
            console.error('请求输出失败', err);
            tt.showToast({ title: '保存失败', icon: 'none', duration: 2000 });
          },
        });
      },
      fail(err) {
        console.error('获取系统信息失败', err);
      }
    });

    const fromcode = tt.getStorageSync('fromcode');


    if (fromcode !== undefined) {
      this.jifenadd();

    }

  },
  jifenadd() {
    // 积分增加

    const requestUrl = `${url}/index.php/api/points_add.php`;
    // console.log("onLoad", tt.getStorageSync('userid'));
    const options = {
      url: requestUrl,
      data: {
        user_id: this.data.op_num,
        ticket_title: 902,
        Invitee_open_id: tt.getStorageSync('open_id'),
        Invitee_image: this.data.userInfo.avatarUrl,
        Invitee_name: this.data.userInfo.nickName,
        key: key
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(options);
    tt.request({
      ...options,
      success: (res) => {
        const data = res.data;
        console.log('积分增加:');
        console.log(data);
        if (data.code == 200) {
          tt.showToast({ title: '积分增加成功', icon: 'success', duration: 2000 });

        } else {
          tt.showToast({ title: data.message, icon: 'none', duration: 2000 });
        }
      },
      fail: (err) => {
        console.log(err);
        tt.showToast({ title: '积分增加失败', icon: 'none', duration: 2000 });
      }
    })
    // 积分增加结束
  },
  jifenaddnew(data) {
    // 积分增加

    const requestUrl = `${url}/index.php/api/points_add.php`;
    // console.log("onLoad", tt.getStorageSync('userid'));
    const options = {
      url: requestUrl,
      data: {
        user_id: data,
        ticket_title: 904,
        Invitee_open_id: tt.getStorageSync('open_id'),
        Invitee_image: this.data.userInfo.avatarUrl,
        Invitee_name: this.data.userInfo.nickName,
        key: key
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    console.log(options);
    tt.request({
      ...options,
      success: (res) => {
        const data = res.data;
        console.log('积分增加:');
        console.log(data);
        if (data.code == 200) {
          tt.showModal({

            title: '获得积分 + 50',
            content: '去个人中心查看，领取奖励',


            showCancel: true,
            confirmText: '去查看',
            success: (res) => {
              if (res.confirm) {
                tt.navigateTo({
                  url: '../my/my'
                });
              }
            },
          });

        } else {
          tt.showToast({ title: data.message, icon: 'none', duration: 2000 });
        }
      },
      fail: (err) => {
        console.log(err);
        tt.showToast({ title: '积分增加失败', icon: 'none', duration: 2000 });
      }
    })
    // 积分增加结束
  }
});
